package bootstrap

import (
	"Walker/global"
	"github.com/casbin/casbin/v2"
	"github.com/casbin/casbin/v2/model"
	"github.com/casbin/casbin/v2/util"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"log"
	"strings"
	"time"
)

func InitCasbin() *casbin.SyncedEnforcer {
	//将数据库连接同步给插件， 插件用来操作数据库可以指定表名称
	prefix := global.ConfigValue.GetString("Casbin.Prefix")
	tableName := global.ConfigValue.GetString("Casbin.TableName")
	Adapter, err := gormadapter.NewAdapterByDBUseTableName(global.DB, prefix, tableName)
	if err != nil {
		log.Fatal("创建权限表失败" + err.Error())
	}
	modelConfig := global.ConfigValue.GetString("Casbin.Model")
	model, err := model.NewModelFromString(modelConfig)
	if err != nil {
		log.Fatal("读取验证规则失败" + err.Error())
	}
	e, err := casbin.NewSyncedEnforcer(model, Adapter)
	if err != nil {
		log.Fatal("创建验证器失败" + err.Error())
	}
	//自定义规则
	e.AddFunction("my_func", MyMatch)
	//定时刷新规则
	//_=e.LoadPolicy()
	e.StartAutoLoadPolicy(time.Second * 5)
	return e
}
func MyMatch(args ...interface{}) (interface{}, error) {
	name1 := args[0].(string)
	name2 := args[1].(string)
	//的判断
	if bool := util.KeyMatch2(name1, name2); bool == true {
		return true, nil
	}
	if name1 == name2 {
		return true, nil
	}
	str := strings.Split(name1, "?")
	if str[0] == name2 {
		return true, nil
	}
	if name2 == "*" {
		return true, nil
	}
	return false, nil
}
